@file:Suppress("NAME_SHADOWING")

package com.shakespace.artofandroid.chapter02.messenger

import android.app.Service
import android.content.Intent
import android.os.*
import android.util.Log
import com.shakespace.artofandroid.global.Constants
import com.shakespace.firstlinecode.global.TAG

class MessengerService : Service() {

    class MessengerHandler : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                Constants.MSG_FROM_CLIENT -> {
                    Log.e(this.TAG, "Service handleMessage: ${msg.data["msg"]}")

                    // reply to Client
                    val messenger = msg.replyTo
                    val msg = Message.obtain(null, Constants.MSG_REPLY_TO_CLIENT)
                    val bundle = Bundle().also {
                        it.putString("reply", "have received your msg")
                    }
                    msg.data = bundle
                    messenger.send(msg)
                }

                else -> ""
            }

        }
    }

    override fun onBind(intent: Intent): IBinder {
        val messenger = Messenger(MessengerHandler())
//        val msg = Message.obtain(null, Constants.MSG_FROM_SERVICE_START)
//        messenger.send()
        return messenger.binder
    }
}
